<script setup>
import { ref } from 'vue'
const dialogVisible = ref(false)
const isabled = ref()
isabled
const formModel = ref({
  id: '',
  name: '',
  crops: '',
  fertilizationcycle: '',
  fertilizer: '',
  landparcelid: '',
  starttime: '',
  endtime: '',
  growthcondition: '',
  status: '',
  landresourcename: '',
  order: '',
  oldendtime: '',
  tar: '',
  userid: ''
})
const fertilizationcycle1 = ref('')
const rules = {
  landresourcename: [
    { required: true, message: '请输入所属土地资源名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 40 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入菜地名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 40 个字符', trigger: 'blur' }
  ],
  crops: [{ required: true, message: '请输入种植的蔬菜', trigger: 'blur' }],
  order: [
    { required: true, message: '内容不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const reg = /^[1-9]\d*$/ // 正整数的正则表达式 开头1-9，后边\d0各或者多个
        if (!reg.test(value)) {
          callback(new Error('请输入有效数据'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  fertilizationcycle1: [
    {
      validator: (rule, value, callback) => {
        const reg = /^[1-9]\d*$/ // 正整数的正则表达式 开头1-9，后边\d0各或者多个
        if (!reg.test(value)) {
          callback(new Error('请输入有效数据'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
const daterange = ref([]) // 存储选择的日期范围
const Datemid = ref()
const pickerOptions = (time) => {
  const now = new Date() // 获取当前日期
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()) // 今天的日期
  let startDate = new Date(Datemid.value)
  startDate.setDate(startDate.getDate() - 1) // 将日期减去一天
  if (formModel.value.id) {
    return time.getTime() < startDate.getTime()
  }
  return time.getTime() < today.getTime() // 禁用过去的日期
}
const form = ref()
const emit = defineEmits(['success'])
import {
  uservegetableinfoAddService,
  uservegetableinfoUpService
} from '@/api/user/vegetableplot'
import { useUserStore } from '@/stores'
const sureQuire = async () => {
  formModel.value.tar = '1'
  await form.value.validate()
  formModel.value.fertilizationcycle = `${fertilizationcycle1.value}天/次`
  const isEdit = formModel.value.id
  if (fertilizationcycle1.value != '' && fertilizationcycle1.value <= 0) {
    ElMessage.error('施肥周期数值不合理')
  } else if (formModel.value.starttime == undefined) {
    ElMessage.error('种植周期不能为空')
  } else {
    if (isEdit) {
      uservegetableinfoUpService(formModel.value)
        .then((response) => {
          if (response.data.status === 200) {
            ElMessage.success(response.data.message)
            dialogVisible.value = false
            emit('success')
          } else {
            dialogVisible.value = false
            ElMessage.error(response.data.message)
          }
        })
        .catch((error) => {
          ElMessage.error(error)
        })
    } else {
      formModel.value.userid = `${useUserStore().user.id}`
      uservegetableinfoAddService(formModel.value)
        .then((response) => {
          if (response.data.status == '200') {
            dialogVisible.value = false
            emit('success')
            ElMessage.success(response.data.message)
          } else {
            dialogVisible.value = false
            ElMessage.error(response.data.message)
          }
        })
        .catch((error) => {
          ElMessage.error(error)
        })
    }
    console.log(formModel.value.starttime)
    fertilizationcycle1.value = ''
    daterange.value = ''
    Datemid.value = ''
  }
}
const NoQuire = () => {
  form.value.resetFields()
  fertilizationcycle1.value = ''
  daterange.value = ''
  dialogVisible.value = false
  Datemid.value = ''
}
const handleClose = () => {
  form.value.resetFields()
  fertilizationcycle1.value = ''
  daterange.value = ''
  dialogVisible.value = false
  Datemid.value = ''
}
const handleClearValidate = () => {}

//
const open = (row) => {
  dialogVisible.value = true
  formModel.value = { ...row } //添加的话，重置表单内容
  if (formModel.value.id) {
    Datemid.value = formModel.value.starttime
    fertilizationcycle1.value = parseInt(
      formModel.value.fertilizationcycle.match(/\d+/)[0],
      10
    )
    daterange.value = [formModel.value.starttime, formModel.value.endtime]
    console.log(daterange.value)
    formModel.value.oldendtime = formModel.value.endtime
    isabled.value = true
  } else {
    isabled.value = false
  }
}
// 处理日期变化事件
const handleDateChange = () => {
  ;[formModel.value.starttime, formModel.value.endtime] = daterange.value
}
defineExpose({
  open
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '修改' : '添加'"
    width="550"
    :before-close="handleClose"
  >
    <el-form
      class="el-form"
      :rules="rules"
      ref="form"
      :model="formModel"
      :before-close="handleClearValidate"
    >
      <el-form-item
        prop="landresourcename"
        label="菜地所属的土地资源名称"
        required="true"
      >
        <el-input
          v-model="formModel.landresourcename"
          :prefix-icon="User"
          placeholder="请输入"
          style="width: 410px"
          :disabled="isabled"
        ></el-input>
      </el-form-item>
      <el-form-item prop="name" label="菜地的名称" required="true">
        <el-input
          v-model="formModel.name"
          :prefix-icon="User"
          placeholder="请输入"
          style="width: 450px"
        ></el-input>
      </el-form-item>
      <el-form-item prop="crops" label="种植的蔬菜" required="true">
        <el-input
          v-model="formModel.crops"
          :prefix-icon="User"
          placeholder="请输入"
          style="width: 450px"
        ></el-input>
      </el-form-item>
      <el-form-item prop="order" label="所属土地资源块数编号" required="true">
        <el-input
          v-model="formModel.order"
          :prefix-icon="User"
          placeholder="请输入"
          style="width: 90px"
          type="number"
          min="1"
          :disabled="isabled"
        ></el-input>
      </el-form-item>
      <el-form-item prop="fertilizationcycle" label="施肥周期">
        <el-input
          v-model="fertilizationcycle1"
          :prefix-icon="User"
          style="width: 80px"
          type="number"
          min="1"
        ></el-input
        ><strong>天/次</strong>
      </el-form-item>
      <el-form-item label="种植周期" required="true">
        <el-date-picker
          v-model="daterange"
          type="daterange"
          :disabledDate="pickerOptions"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
          :size="size"
          @change="handleDateChange"
          style="width: 200px"
      /></el-form-item>
      <el-form-item prop="fertilizer" label="肥料类型">
        <el-input
          v-model="formModel.fertilizer"
          :prefix-icon="User"
          style="width: 120px"
        ></el-input>
      </el-form-item>
      <el-form-item prop="growthcondition" label="生长状况">
        <el-input
          v-model="formModel.growthcondition"
          :prefix-icon="User"
          :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea"
          style="width: 450px"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="NoQuire">取消</el-button>
        <el-button type="primary" @click="sureQuire"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style>
.el-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}
</style>
